package com.mini.framework.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mini.framework.core.ApplicationContext;
import com.mini.framework.web.RequestHandler;
import com.mini.framework.web.WebApplicationContext;


public class MiniServletDispatcher extends HttpServlet {
	
	private ApplicationContext applicationContext;
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		dispatcher(request,response);
	}
	
	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		dispatcher(request,response);
	}
	
	private void dispatcher(HttpServletRequest request,HttpServletResponse response){
		String requestUrl = request.getRequestURI();
		String contextPath = request.getContextPath();
		String requestMapUrl = requestUrl.substring(contextPath.length());
		RequestHandler requestHandler = applicationContext.getBean(requestMapUrl);
		if(requestHandler != null){
			Object[] params = getParams(request,response,requestHandler);
			Object ret = requestHandler.invoke(params);
			requestHandler.getViewHandler().render(request, response,ret);
		}else{
			
		}
	}
	
	private Object[] getParams(HttpServletRequest request,HttpServletResponse response,RequestHandler handler){
		String[] paramClassNames = handler.getParamClassNames();
		Object[] objs = new Object[paramClassNames.length];
		for(int i=0;i<paramClassNames.length;i++){
			if(paramClassNames[i].equals(HttpRequestResponse.HTTP_REQUEST)){
				objs[i] = request;
			}
			if(paramClassNames[i].equals(HttpRequestResponse.HTTP_RESPONSE)){
				objs[i] = response;
			}
		}
		return objs;
	}
	
	@Override
	public void init(){
		applicationContext = new WebApplicationContext();
	}
	
	interface HttpRequestResponse{
		String HTTP_REQUEST = HttpServletRequest.class.getName();
		String HTTP_RESPONSE = HttpServletResponse.class.getName();
		
	}

}
